<template>
  <div class="box">
    <!-- 顶部导航栏 -->
    <div class="header-container">
        <span v-if="status === 1"
              class="businessBtn">营业中</span>
      <span v-else
            class="businessBtn closing">打烊中</span>
      <div :key="restKey"
           class="right-menu">
        <div class="avatar-wrapper">
          <!--    菜单栏      -->
          <el-dropdown>
            <!--     头像       -->
            <div class="avatar-container">
              <el-avatar :size="50" fit="cover" class="custom-avatar"
                         v-if="avatar" :src="avatar"/>
              <el-avatar :size="50" fit="cover" class="custom-avatar"
                         v-else icon="el-icon-user-solid"/>
            </div>
            <el-dropdown-menu slot="dropdown" class="el-dropdown-menu">
              <el-dropdown-item @click.native="userInfo()">
                <i class="iconfont icon-icon-test35"/>
                个人信息
              </el-dropdown-item>
              <el-dropdown-item @click.native="addressInfo()">
                <i class="iconfont icon-icon-test20"/>
                地址信息
              </el-dropdown-item>
              <el-dropdown-item @click.native="updatePwd()">
                <i class="iconfont icon-mima"/>
                修改密码
              </el-dropdown-item>
              <el-dropdown-item @click.native="logout()">
                <i class="iconfont icon-tuichu"/>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="avatar-wrapper">
          <router-link to="/shoppingCart">
            <span class="el-dropdown-link" style="color: white;margin-top: 10px;font-size: 20px">
              <el-badge :value="num">
                <i v-if="this.num > 0" class="iconfont icon-icon-test11" style="font-size: 24px;"/>
                <i v-else class="iconfont icon-icon-test10" style="font-size: 24px;"/>
              </el-badge>
              购物车
            </span>
          </router-link>
        </div>

        <div class="avatar-wrapper">
          <router-link to="/orders">
            <span class="el-dropdown-link" style="color: black;margin-top: 10px;font-size: 20px;">
                <i class="el-icon-s-order" style="font-size: 24px;"/>
              我的订单
            </span>
          </router-link>
        </div>
      </div>
    </div>

    <!-- 个人资料弹层 -->
    <UserInfo ref="userInfoDialog" @imageAvatarSuccess="uploadImage"/>

    <!-- 地址簿弹层 -->
    <AddressInfo ref="addressInfoDialog"/>

    <!--  修改密码弹层  -->
    <EditPwd ref="editPwdDialog"/>

    <el-container class="heightAll">
      <!--   侧边栏   -->
      <div class="aside">
        <el-aside class="el-aside">
          <div class="logo">
            <div class="sidebar-logo">
              <img src="@/assets/jindowin_w.png" style="width: 200px;height: 50px;margin-right: 100px;margin-top: 10px">
            </div>
          </div>
          <el-menu
              default-active="10"
              class="el-menu-vertical-demo"
              background-color="#545c64"
              text-color="#fff"
              active-text-color="#FFC200">
            <el-menu-item
                v-for="item in menuItems"
                :key="item.id"
                :index="item.id"> <!--使用 id 作为 index-->
              <span style="font-size: 18px;margin-right: 100px;">{{ item.name }}</span> <!-- 显示 name 字段 -->
            </el-menu-item>
          </el-menu>
        </el-aside>
      </div>

      <!--   表格   -->
      <el-main>
        <div class="dashboard-container">
          <div class="container">
            <div class="tableBar">
              <el-page-header style="float: left" @back="goBack" content="首页"/>
              <label style="margin-right: 100px;font-size: 40px">我的订单</label>
            </div>
          </div>
          <div class="tableBar">

            <el-badge :value="null" class="item">
              <el-button
                  style="float: left"
                  :class="{ 'black-btn': selectedButton === null }"
                  type="primary"
                  @click="pageQuery(null)">
                全部订单
              </el-button>
            </el-badge>

            <el-badge :value="pendingPayment" class="item">
              <el-button
                  style="float: left; position: relative;"
                  :class="{ 'black-btn': selectedButton === 1 }"
                  type="primary"
                  @click="pageQuery(1)">
                待付款
              </el-button>
            </el-badge>

            <el-badge :value="toBeConfirmed" class="item">
              <el-button
                  style="float: left"
                  :class="{ 'black-btn': selectedButton === 2 }"
                  type="primary"
                  @click="pageQuery(2)">
                待接单
              </el-button>
            </el-badge>

            <el-badge :value="confirmed" class="item">
              <el-button
                  style="float: left"
                  :class="{ 'black-btn': selectedButton === 3 }"
                  type="primary"
                  @click="pageQuery(3)">
                待派送
              </el-button>
            </el-badge>

            <el-badge :value="deliveryInProgress" class="item">
              <el-button
                  style="float: left"
                  :class="{ 'black-btn': selectedButton === 4 }"
                  type="primary"
                  @click="pageQuery(4)">
                派送中
              </el-button>
            </el-badge>

          </div>
          <el-table v-if="orderList && orderList.length > 0"
                    :data="orderList"
                    stripe
                    class="tableBox">
            <el-table-column prop="number"
                             label="订单编号"/>
            <el-table-column label="图片">
              <template v-slot="scope">
                <template v-if="scope.row.images && scope.row.images.length">
                  <el-image
                      v-for="(image, index) in scope.row.images"
                      :key="index"
                      style="width: 40px; height: 40px; border: none; cursor: pointer"
                      :src="image">
                    <div slot="error" class="image-slot">
                      <img src="@/assets/noImg.png" style="width: auto; height: 40px; border: none">
                    </div>
                  </el-image>
                </template>
                <template v-else>
                  <img src="@/assets/noImg.png" style="width: auto; height: 40px; border: none">
                </template>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template v-slot="scope">
                <span style="margin-right: 10px">￥{{ (scope.row.amount).toFixed(2) * 100 / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单状态">
              <template v-slot="scope">
                <span style="margin-right: 10px;" class="blueBug">
                  <template v-if="scope.row.status === 1">
                    待付款
                  </template>
                  <template v-else-if="scope.row.status === 2">
                    已付款
                  </template>
                  <template v-else-if="scope.row.status === 3">
                    已接单
                  </template>
                  <template v-else-if="scope.row.status === 4">
                    派送中
                  </template>
                  <template v-else-if="scope.row.status === 5">
                    已完成
                  </template>
                  <template v-else-if="scope.row.status === 6">
                    已取消
                  </template>
                  <template v-else-if="scope.row.status === 7">
                    已退款
                  </template>
                </span>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="250"
                align="center">
              <template v-slot="scope">
                <el-button
                    v-if="selectedButton === null"
                    type="text"
                    @click="handleAgain(scope.row.id)">
                  再来一单
                </el-button>
                <el-button
                    v-if="selectedButton === 2 || selectedButton === 3"
                    type="text"
                    @click="handleReminder(scope.row.id)">
                  催单
                </el-button>
                <el-button
                    v-if="selectedButton === 1"
                    type="text"
                    @click="handleToPay(scope.row)">
                  去付款
                </el-button>
                <el-button
                    v-if="selectedButton === 1"
                    type="text"
                    class="redBug"
                    @click="handleCancel(scope.row.id)">
                  取消订单
                </el-button>
                <el-button
                    v-if="selectedButton === 4"
                    type="text"
                    @click="handleCompleted(scope.row.id)">
                  确认收货
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <Empty v-else
                 :is-search="isSearch"/>
          <el-pagination
              class="pageList"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>

        </div>
      </el-main>


    </el-container>

  </div>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
import EditPwd from "@/components/EditPwd/index.vue";
import AddressInfo from "@/components/AddressInfo/index.vue";
import Empty from "@/components/Empty/index.vue";
import UserInfo from "@/components/UserInfo/index.vue";
import {getUserInfo} from "@/api/user";
import {getShoppingCartSum} from "@/api/shoppingcart";
import {getList} from "@/api/category";
import axios from "axios";
import {again, alipay, cancel, completed, getOrderById, getOrderList, ordersCount, reminder} from "@/api/order";

@Component({
  components: {UserInfo, Empty, AddressInfo, EditPwd}
})
export default class index extends Vue {
  private page = 1
  private pageSize = 10
  private total = 0
  private avatar = ''
  private orderList: any[] = []
  private isSearch = false
  private menuItems = []
  private restKey = 0
  private setStatus = 1
  private status = 1
  private id = ''
  private num = 0
  private number = ''   //订单号
  private selectedButton = null
  private pendingPayment = 0  // 待付款
  private toBeConfirmed = 0   // 待接单
  private confirmed = 0       // 待派送
  private deliveryInProgress = 0   // 派送中

  private uploadImage(newImage: string) {
    this.avatar = newImage;
  }

  created() {
    this.getStatus();
    this.getCount();
    this.pageQuery(1);
    this.getUserAvatar();
    this.getShoppingCartCount();
    this.fetchMenuItems();
  }

  handleToPay(row) {
    getOrderById(row.id).then(res => {
      sessionStorage.setItem("totalPrice", row.amount);
      if (res.data.code === 1) {
        const params = {
          subject: res.data.data.consignee,
          traceNo: row.number,
          totalAmount: row.amount,
        }
        alipay(params).then(res => {
          if (res.data.code === 1) {
            console.log(res.data.data);
            document.write(res.data.data);
            this.$nextTick(() => {
              // 提交支付表单
              const alipayWap = this.$refs.alipayWap as HTMLElement;
              const form = alipayWap.children[0] as HTMLFormElement;
              if (form) {
                form.submit();
              }
              setTimeout(() => {
                // this.toPayFlag = false;
              }, 500);
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    })
  }


  handleAgain(id: any) {
    again(id).then((res) => {
      if (res.data.code === 1) {
        this.$router.push({path: "/shoppingCart"})
      } else {
        this.$message.error(res.data.msg);
      }
    }).catch(err => {
      this.$message.error(err.message);
    })
  }

  handleCompleted(id: any) {
    completed(id).then((res) => {
      if (res.data.code === 1) {
        this.$message.success("成功确认收货");
        this.pageQuery(this.selectedButton);
        this.getCount();
      } else {
        this.$message.error(res.data.msg);
      }
    }).catch(err => {
      this.$message.error(err.message);
    })
  }

  handleReminder(id: any) {
    reminder(id).then(res => {
      if (res.data.code === 1) {
        this.$message.success("已向商家发送催促信息")
      } else {
        this.$message.error(res.data.msg);
      }
    }).catch(err => {
      this.$message.error(err.message);
    })
  }

  handleCancel(id: any) {
    this.$confirm('是否取消订单?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      cancel(id).then(res => {
        if (res.data.code === 1) {
          this.$message.success("成功取消订单");
          this.pageQuery(this.selectedButton);
          this.getCount();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    })
  }

  getCount() {
    ordersCount().then(res => {
      if (res.data.code === 1) {
        this.pendingPayment = res.data.data.pendingPayment;
        this.toBeConfirmed = res.data.data.toBeConfirmed;
        this.confirmed = res.data.data.confirmed;
        this.deliveryInProgress = res.data.data.deliveryInProgress;
      }
    })
  }

  pageQuery(status) {
    const params = {
      page: this.page,
      pageSize: this.pageSize,
      status: status
    }
    this.selectedButton = status;
    getOrderList(params).then(res => {
      if (res.data.code === 1) {
        this.total = res.data.data.total;
        //console.log('原始数据:', JSON.stringify(res.data.data.records, null, 2));

        try {
          this.orderList = res.data.data.records.map(order => {
            //console.log('处理订单:', order);
            return {
              id: order.id,
              number: order.number,
              amount: order.amount,
              status: order.status,
              images: order.orderDetails ? order.orderDetails.map(detail => detail.image) : []
            };
          });
          //console.log('映射后的数据:', JSON.stringify(this.orderList, null, 2));
        } catch (error) {
          console.error('数据映射错误:', error);
        }
      }
    }).catch(error => {
      console.error('获取订单列表失败:', error);
    });
  }


  getUserAvatar() {
    getUserInfo().then(res => {
      if (res.data.code === 1) {
        this.avatar = res.data.data.avatar;
      }
    })
  }

  getShoppingCartCount() {
    getShoppingCartSum().then((res) => {
      if (res.data.code === 1) {
        this.num = res.data.data
      }
    })
  }

  handleSizeChange(pageSize: number) {
    this.pageSize = pageSize;
    this.pageQuery(this.selectedButton);
  }

  handleCurrentChange(page: number) {
    this.page = page;
    this.pageQuery(this.selectedButton);
  }


  fetchMenuItems() {
    getList().then(res => {
      this.menuItems = res.data.data;
    })
  }

  addressInfo() {
    (this.$refs.addressInfoDialog as any).dialogAddressVisible = true;
  }

  userInfo() {
    (this.$refs.userInfoDialog as any).dialogVisible = true;
  }

  updatePwd() {
    (this.$refs.editPwdDialog as any).dialogFormVisible = true;  // 调用子组件中的属性
  }

  getStatus() {
    const token = sessionStorage.getItem('authentication')

    axios({
      method: "get",
      url: "/api/user/shop/status",
      headers: {
        authentication: token
      }
    }).then(res => {
      if (res.data.code === 1) {
        this.status = res.data.data
        this.setStatus = this.status
      }
    }).catch(err => {
      this.$message.error(err.message);
    })
  }

  goBack() {
    this.$router.push({
      path: '/index'
    })
  }

  logout() {
    this.$router.push({
      path: '/'
    })
  }

}
</script>


<style lang="scss" scoped>
.custom-avatar {
  display: flex; /* 设为 Flexbox 布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  margin: 0; /* 清除任何外边距 */
  padding: 0; /* 清除任何内边距 */
}

.avatar-container {
  width: 50px;
  height: 50px;
}

a {
  text-decoration: none;
}

.aside {
  width: 200px;
  background-color: #FFC200;
  height: 100vh;
  overflow: hidden;
  overflow-y: auto;
}

.el-aside {
  width: 200px;
  height: 100vh;
  overflow: hidden;
}

.logo {
  background-color: #FFC200; /* 设置背景颜色 */
  z-index: 1000; /* 确保它位于其他内容之上 */
  position: fixed;
}

.heightAll {
  height: 100%;
}

.el-menu-vertical-demo {
  margin-top: 53px;
  padding-top: 20px;
  height: 100%;
}

.item {
  top: 10px;
  margin-right: 20px;
}

.el-button {
  margin-bottom: 20px;
}

.blueBug {
  color: #419EFF !important;
  position: relative;
}

.black-btn {
  background-color: #20232A !important; /* 设为黑色背景 */
  border: none !important; /* 移除边框 */
}

.redBug {
  color: #ff0000 !important;
  position: relative;
}

.blueBug::after {
  position: absolute;
  right: -6px;
  height: 14px;
  width: 0px;
  border-right: solid 1px #EBEEF5 !important;
}

.dashboard {
  &-container {
    margin: 60px;

    .container {
      background: #fff;
      position: relative;
      z-index: 1;
      padding: 30px 28px;
      border-radius: 4px;

      .tableBar {
        gap: 10px; /* 组件间距，也可以使用 margin */

      }

      .tableBox {
        width: 100%;
        border: 1px solid #F3F4F7;
        border-bottom: 0;
      }

      .pageList {
        text-align: center;
        margin-top: 30px;
      }

      .normal-btn {
        background: #303133;
        color: white;
        margin-left: 20px;
      }
    }
  }
}
</style>
<style scoped>

.el-dropdown-link {
  cursor: pointer;
  font-size: 15px;
  margin-top: -5px;
}

.el-icon-arrow-down {
  font-size: 20px;
  line-height: 50px;
}

.header-container {
  background: #FFC200;
  position: fixed; /* 固定在页面顶部 */
  top: 0; /* 从顶部开始 */
  left: 0; /* 从左侧开始 */
  right: 0; /* 直到右侧 */
  height: 72px; /* 设置导航栏高度，根据需求调整 */
  z-index: 1000;
}

.box {
  position: fixed;
  width: 100%;
  height: 100%;
}

.businessBtn {
  height: 20px;
  line-height: 20px;
  background: #fd3333;
  border: 1px solid #ffffff;
  border-radius: 4px;
  display: inline-block;
  padding: 0 6px;
  margin-top: 25px;
  color: #fff;


}

.closing {
  background: #606266;
}

.right-menu {
  float: right;
  margin-right: 20px;
  color: #333333;
  font-size: 14px;

  span {
    width: 130px;
    display: inline-block;
    cursor: pointer;

    &:hover {
      background: rgba(255, 255, 255, 0.52);
    }
  }

  &:focus {
    outline: none;
  }

  .avatar-wrapper {
    margin-top: 14px;
    margin-left: 18px;
    position: relative;
    float: right;
    width: 120px;
    text-align: left;
  }
}


</style>
